<?php
/**
 *
 * Author: LiuJianPeng
 * Date: 2023/8/8
 * Time: 9:55
 */

namespace App\Service\Core\Admin\LoginLog;

use App\Component\ListService\ListAbstract;
use App\Model\Core\Admin\AdminLoginLogModel;
use App\Service\ParamsService;

/**
 * @method  $this setStartTime($val)
 * @method  $this setEndTime($val)
 * @method  $this setKeyword($val)
 */
class AdminLoginLogListService extends ListAbstract
{

    protected array $default_sort_by = ['login_at' => 'desc'];
    protected array $allow_sort = ['login_at'];

    //扩展字段
    protected array $allow_ext_fields = ['source_name'];

    protected function getQueryObj()
    {
        // TODO: Implement getQueryObj() method.
        $query_obj = AdminLoginLogModel::getInstance()->getConnectionTable();

        //操作时间
        $start_time = $this->getParam('start_time');
        if (!empty($start_time)) {
            $start_time = date('Y-m-d H:i:s', strtotime($start_time));
            $query_obj->where('operate_at', '>=', $start_time);
        }

        $end_time = $this->getParam('end_time');
        if (!empty($end_time)) {
            $end_time = date('Y-m-d 23:59:59', strtotime($end_time));
            $query_obj->where('operate_at', '<=', $end_time);
        }

        //搜索关键词
        $keyword = $this->getParam('keyword');
        if (!empty($keyword)) {
            $query_obj->where('username', 'like', '%' . $keyword . '%');
        }

        return $query_obj;
    }

    /**
     * 扩展字段
     * @param array $row
     * @return array
     */
    protected function getExtField(array $row): array
    {
        //来源
        if (easy_in_array('source_name', $this->ext_fields)) {
            $row['source_name'] = ParamsService::$admin_login_log_source[$row['source']];
        }
        return $row;
    }
}
